<template>
  <view class="filter-bar">
    <!-- 筛选标签 -->
    <scroll-view 
      class="filter-bar__scroll" 
      scroll-x 
      :show-scrollbar="false"
      :enhanced="true"
    >
      <view class="filter-bar__content">
        <!-- 筛选项 -->
        <view 
          v-for="(filter, index) in filters" 
          :key="filter.key"
          class="filter-bar__item"
          :class="{
            'filter-bar__item--active': isActive(filter),
            'filter-bar__item--dropdown': filter.type === 'dropdown'
          }"
          @click="handleFilterClick(filter, index)"
        >
          <text class="filter-bar__item-text">{{ getFilterText(filter) }}</text>
          <u-icon 
            v-if="filter.type === 'dropdown'" 
            name="arrow-down" 
            size="24rpx" 
            :color="isActive(filter) ? '#ffffff' : '#666666'"
            :class="{ 'filter-bar__icon--rotate': activeDropdown === index }"
          ></u-icon>
        </view>
        
        <!-- 重置按钮 -->
        <view 
          v-if="showReset && hasActiveFilters"
          class="filter-bar__reset"
          @click="handleReset"
        >
          <u-icon name="refresh" size="24rpx" color="#666"></u-icon>
          <text class="filter-bar__reset-text">{{ $t('common.reset') }}</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- 下拉选项 -->
    <view 
      v-if="activeDropdown !== null && currentDropdownOptions.length"
      class="filter-bar__dropdown"
    >
      <view class="filter-bar__dropdown-content">
        <view 
          v-for="option in currentDropdownOptions" 
          :key="option.value"
          class="filter-bar__dropdown-item"
          :class="{ 'filter-bar__dropdown-item--active': isOptionSelected(option) }"
          @click="handleOptionClick(option)"
        >
          <text class="filter-bar__dropdown-text">{{ option.label }}</text>
          <u-icon 
            v-if="isOptionSelected(option)"
            name="checkmark" 
            size="32rpx" 
            color="var(--primary-color, #007AFF)"
          ></u-icon>
        </view>
      </view>
    </view>
    
    <!-- 遮罩层 -->
    <view 
      v-if="activeDropdown !== null"
      class="filter-bar__mask"
      @click="closeDropdown"
    ></view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'

interface FilterOption {
  label: string
  value: any
}

interface Filter {
  key: string
  label: string
  type: 'toggle' | 'dropdown'
  value?: any
  options?: FilterOption[]
  multiple?: boolean // 是否支持多选（仅dropdown类型）
}

interface Props {
  // 筛选配置
  filters: Filter[]
  // 当前筛选值
  modelValue: Record<string, any>
  // 是否显示重置按钮
  showReset?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  showReset: true
})

interface Emits {
  'update:modelValue': [value: Record<string, any>]
  change: [key: string, value: any]
  reset: []
}

const emit = defineEmits<Emits>()

// 响应式数据
const activeDropdown = ref<number | null>(null)
const filterValues = ref<Record<string, any>>({ ...props.modelValue })

// 计算属性
const hasActiveFilters = computed(() => {
  return Object.keys(filterValues.value).some(key => {
    const value = filterValues.value[key]
    return value !== undefined && value !== null && value !== '' && 
           (Array.isArray(value) ? value.length > 0 : true)
  })
})

const currentDropdownOptions = computed(() => {
  if (activeDropdown.value === null) return []
  const filter = props.filters[activeDropdown.value]
  return filter?.options || []
})

// 监听外部值变化
watch(() => props.modelValue, (newValue) => {
  filterValues.value = { ...newValue }
}, { deep: true })

// 监听内部值变化
watch(filterValues, (newValue) => {
  emit('update:modelValue', { ...newValue })
}, { deep: true })

// 判断筛选项是否激活
const isActive = (filter: Filter): boolean => {
  const value = filterValues.value[filter.key]
  if (filter.type === 'toggle') {
    return !!value
  } else if (filter.type === 'dropdown') {
    if (filter.multiple) {
      return Array.isArray(value) && value.length > 0
    } else {
      return value !== undefined && value !== null && value !== ''
    }
  }
  return false
}

// 获取筛选项显示文本
const getFilterText = (filter: Filter): string => {
  const value = filterValues.value[filter.key]
  
  if (filter.type === 'toggle') {
    return filter.label
  } else if (filter.type === 'dropdown') {
    if (!value || (Array.isArray(value) && value.length === 0)) {
      return filter.label
    }
    
    if (filter.multiple && Array.isArray(value)) {
      if (value.length === 1) {
        const option = filter.options?.find(opt => opt.value === value[0])
        return option?.label || filter.label
      } else {
        return `${filter.label}(${value.length})`
      }
    } else {
      const option = filter.options?.find(opt => opt.value === value)
      return option?.label || filter.label
    }
  }
  
  return filter.label
}

// 判断选项是否被选中
const isOptionSelected = (option: FilterOption): boolean => {
  if (activeDropdown.value === null) return false
  
  const filter = props.filters[activeDropdown.value]
  const value = filterValues.value[filter.key]
  
  if (filter.multiple) {
    return Array.isArray(value) && value.includes(option.value)
  } else {
    return value === option.value
  }
}

// 事件处理
const handleFilterClick = (filter: Filter, index: number) => {
  if (filter.type === 'toggle') {
    const currentValue = filterValues.value[filter.key]
    const newValue = !currentValue
    filterValues.value[filter.key] = newValue
    emit('change', filter.key, newValue)
  } else if (filter.type === 'dropdown') {
    if (activeDropdown.value === index) {
      closeDropdown()
    } else {
      activeDropdown.value = index
    }
  }
}

const handleOptionClick = (option: FilterOption) => {
  if (activeDropdown.value === null) return
  
  const filter = props.filters[activeDropdown.value]
  
  if (filter.multiple) {
    const currentValue = filterValues.value[filter.key] || []
    let newValue: any[]
    
    if (currentValue.includes(option.value)) {
      newValue = currentValue.filter((v: any) => v !== option.value)
    } else {
      newValue = [...currentValue, option.value]
    }
    
    filterValues.value[filter.key] = newValue
    emit('change', filter.key, newValue)
  } else {
    const currentValue = filterValues.value[filter.key]
    const newValue = currentValue === option.value ? undefined : option.value
    
    filterValues.value[filter.key] = newValue
    emit('change', filter.key, newValue)
    closeDropdown()
  }
}

const closeDropdown = () => {
  activeDropdown.value = null
}

const handleReset = () => {
  filterValues.value = {}
  emit('reset')
  closeDropdown()
}
</script>

<style lang="scss" scoped>
.filter-bar {
  position: relative;
  background: var(--card-bg-color, #ffffff);
  border-bottom: 2rpx solid var(--border-color-light, #f0f0f0);
}

.filter-bar__scroll {
  white-space: nowrap;
}

.filter-bar__content {
  display: flex;
  align-items: center;
  padding: 24rpx 32rpx;
  gap: 24rpx;
}

.filter-bar__item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 16rpx 24rpx;
  background: var(--bg-color-light, #f8f9fa);
  border-radius: 32rpx;
  transition: all 0.3s ease;
  white-space: nowrap;
  flex-shrink: 0;
  
  &:active {
    transform: scale(0.95);
  }
  
  &--active {
    background: var(--primary-color, #007AFF);
    
    .filter-bar__item-text {
      color: #ffffff;
    }
  }
  
  &--dropdown {
    .filter-bar__icon--rotate {
      transform: rotate(180deg);
    }
  }
}

.filter-bar__item-text {
  font-size: 26rpx;
  color: var(--text-color, #333333);
  font-weight: 500;
  transition: color 0.3s ease;
}

.filter-bar__reset {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 16rpx 24rpx;
  background: var(--bg-color-light, #f8f9fa);
  border-radius: 32rpx;
  transition: all 0.2s ease;
  white-space: nowrap;
  flex-shrink: 0;
  
  &:active {
    transform: scale(0.95);
    background: var(--bg-color, #e9ecef);
  }
}

.filter-bar__reset-text {
  font-size: 26rpx;
  color: var(--text-color-secondary, #666666);
  font-weight: 500;
}

.filter-bar__dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 100;
  background: var(--card-bg-color, #ffffff);
  border-radius: 0 0 16rpx 16rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  max-height: 400rpx;
  overflow-y: auto;
}

.filter-bar__dropdown-content {
  padding: 16rpx 0;
}

.filter-bar__dropdown-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 32rpx;
  transition: all 0.2s ease;
  
  &:active {
    background: var(--bg-color-light, #f8f9fa);
  }
  
  &--active {
    background: rgba(0, 122, 255, 0.05);
    
    .filter-bar__dropdown-text {
      color: var(--primary-color, #007AFF);
      font-weight: 600;
    }
  }
}

.filter-bar__dropdown-text {
  font-size: 28rpx;
  color: var(--text-color, #333333);
  transition: all 0.2s ease;
}

.filter-bar__mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99;
  background: rgba(0, 0, 0, 0.3);
}

// 响应式设计
@media (max-width: 750rpx) {
  .filter-bar__content {
    padding: 20rpx 24rpx;
    gap: 20rpx;
  }
  
  .filter-bar__item {
    padding: 12rpx 20rpx;
  }
  
  .filter-bar__item-text {
    font-size: 24rpx;
  }
  
  .filter-bar__reset {
    padding: 12rpx 20rpx;
  }
  
  .filter-bar__reset-text {
    font-size: 24rpx;
  }
}

// 暗色主题适配
[data-theme='dark'] {
  .filter-bar {
    --card-bg-color: #1c1c1e;
    --text-color: #ffffff;
    --text-color-secondary: #8e8e93;
    --bg-color-light: #2c2c2e;
    --bg-color: #3a3a3c;
    --border-color-light: #38383a;
  }
}
</style>